// 导出创建切片的方法
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { ListItemRawState } from '../../types'
import { createListenerEntry } from '@reduxjs/toolkit/dist/listenerMiddleware'

export interface CartRawState extends ListItemRawState {
  count: number
  state: boolean
}

// 创建切片并且抛出
const cartSlice = createSlice({
  // 模块名称 | 命名空间
  name: 'cartSlice',
  // 模块初始化数据
  initialState: {
    cartList: [] as CartRawState[]
  },
  // 纯函数 --- 修改数据
  reducers: {
    // 加入购物车
    addCartList(state, action: PayloadAction<CartRawState>) {
      // 1. 查重
      const item = state.cartList.find(v => v.id === action.payload.id)
      // 2. 存在
      if (item) {
        item.count++
      }
      // 3. 不存在
      else {
        state.cartList.push(action.payload)
      }
    },
    // 减少购物车
    subCartList(state, action: PayloadAction<CartRawState>) {
      // 1. 根据 id 查找
      const item = state.cartList.find(v => v.id === action.payload.id)
      // 2. 是否存在
      if (item) {
        item.count--
      }
    },
    // 单项状态切换
    switchState(state, action: PayloadAction<CartRawState>) {
      // 1. 根据 id 查找
      const item = state.cartList.find(v => v.id === action.payload.id)
      // 2. 是否存在
      if(item) {
        item.state = !item.state
      }
    },
    // 删除单项数据
    deleteCarList(state, action: PayloadAction<CartRawState>) {
      // 直接删除
      state.cartList = state.cartList.filter(v => v.id !== action.payload.id)
    },
    // 全选状态切换
    totalSwitchState(state, action: PayloadAction<boolean>) {
      state.cartList.forEach(v => v.state = action.payload)
    },
    // 多选删除选中数据
    deleteSelectedCartList(state) {
      state.cartList = state.cartList.filter(v => !v.state)
    }
  }
})


export default cartSlice.reducer

export const { addCartList, subCartList, switchState, deleteCarList, totalSwitchState, deleteSelectedCartList } = cartSlice.actions


